import React, { Component } from 'react'
import { connect } from 'dva'
import {
  Select,
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  message,
  Table,
  Upload,
  Icon,
  Modal,
} from 'antd'
import Cookies from 'universal-cookie'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import PModal from './PropModal'
import columns from '../propList/columns'
import styles from './Index.less'
import settings from '@/../config/defaultSettings'
import { uploadDataConvert, itemConvertToUpload } from '@/utils/utils'

const FormItem = Form.Item
const { Option } = Select
const { TextArea } = Input

const cookies = new Cookies()

@connect(({ loading, propRepair }) => ({
  propRepair,
  loading: loading.models.propRepair,
}))
@Form.create()
export default class PropRUpdate extends Component {
  constructor(props) {
    super(props)
    const fileImgList = []

    this.state = {
      // propRecords: [],
      fileImgList,
    }
  }

  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props
    const { currentItem } = this.props.propRepair

    // if (currentItem.id && currentItem.items.length > 0) {
    //   this.setState({
    //     propRecords: currentItem.items,
    //   })
    // }
    dispatch({
      type: 'propRepair/fetchSelectPropData',
      payload: {
        type: 'repair_type',
      },
    })

    if (currentItem.id && currentItem.imgList) {
      this.setState({
        fileImgList: itemConvertToUpload('2', currentItem.imgList),
      })
    }
  }

  componentDidUpdate(prevProps) {
    if (prevProps.propRepair.currentItem.id && !this.props.propRepair.currentItem.id) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({
        fileImgList: [],
      })
    }
  }

  handleDelClick = (record, e) => {
    e.preventDefault()
    const items = [...this.props.propRepair.currentItem.items]
    const index = items.findIndex(item => item.id === record.id)
    items.splice(index, 1)
    this.props.dispatch({
      type: 'propRepair/updateState',
      payload: {
        currentItem: {
          ...this.props.propRepair.currentItem,
          items,
        },
      },
    })
  }

  handleBeforeUpload = file => {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      message.error('文件小于10M')
      return false
    }
  }

  // 文件上传
  handleUplod = (f, type) => {
    if (f.file.status) {
      this.setState({
        [type]: f.fileList,
      })
    }
    if (f.file.status === 'done') {
      if (!f.file.response.success) {
        Modal.error({
          title: '上传错误',
          content: f.file.response.message,
        })
        // this.setState 图片清除
      }
    }
  }

  handleModalClick = selectRecords => {
    this.props.dispatch({
      type: 'propRepair/updateState',
      payload: {
        currentItem: {
          ...this.props.propRepair.currentItem,
          items: selectRecords,
        },
      },
    })

    this.setState({
      showModal: false,
    })
  }

  handleSave() {
    const { dispatch } = this.props
    const { currentItem } = this.props.propRepair
    const { getFieldsValue, validateFields } = this.props.form
    // const { propRecords } = this.state
    const propRecords = currentItem.items || []

    validateFields(errors => {
      if (errors) {
        return
      }

      const data = {
        ...getFieldsValue(),
        id: currentItem.id,
        items: propRecords.map(item => ({
          // 使用资产id
          zcCode: item.id,
          status: item.status,
        })),
        imgList: [],
      }

      if (propRecords.length < 1) {
        message.info('请添加资产')
        return
      }

      if (data.filesImg && data.filesImg.fileList) {
        data.filesImg.fileList.forEach((item, index) => {
          const res = uploadDataConvert(item, index, '2')
          if (res.success) {
            data.imgList.push(res.data)
          }
        })
      }
      delete data.filesImg

      dispatch({
        type: 'propRepair/save',
        payload: data,
      })
    })
  }

  // 资产属性下拉option
  renderOptionNodes(type) {
    const data = this.props.propRepair[type]
    return data.map(item => (
      <Option key={item.id} value={item.keyName}>
        {item.keyValue}
      </Option>
    ))
  }

  // 简单搜索条件
  renderForm() {
    const { currentItem } = this.props.propRepair
    const { getFieldDecorator } = this.props.form
    const { fileImgList } = this.state
    const propRecords = currentItem.items || []
    const AuthHeaders = {
      Authorization: `Bearer${cookies.get('auth_token')}`,
    }

    const tableColumns = [
      ...columns,
      {
        title: '操作',
        align: 'center',
        width: 80,
        // fixed: 'right',
        render: (text, record) => (
          <div>
            <a onClick={e => this.handleDelClick(record, e)}>删除</a>
          </div>
        ),
      },
    ]

    return (
      <Form layout="inline">
        <div className={styles.fieldTitle}>基本信息</div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="报修单名称">
              {getFieldDecorator('repairName', {
                initialValue: currentItem.repairName,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="报修类型">
              {getFieldDecorator('repairType', {
                initialValue: currentItem.repairType,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Select placeholder="请选择">{this.renderOptionNodes('repair_type')}</Select>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={23} offset={1}>
            <FormItem label="资产图片" extra="最多支持5张,图片大小需小于10M">
              {getFieldDecorator('filesImg', {
                initialValue: currentItem.imgList
                  ? { fileList: itemConvertToUpload('2', currentItem.imgList || []) }
                  : null,
              })(
                <Upload
                  showUploadList={{
                    showPreviewIcon: false,
                    showDownloadIcon: false,
                  }}
                  fileList={fileImgList}
                  accept=".jpg,.png,.PNG,.JPG,.JPEG,.jpeg"
                  action={`${settings.URL}/file/upload`}
                  listType="picture-card"
                  onChange={f => {
                    this.handleUplod(f, 'fileImgList')
                  }}
                  beforeUpload={this.handleBeforeUpload}
                  headers={AuthHeaders}
                >
                  {fileImgList.length >= 5 ? null : (
                    <div>
                      <Icon type="plus" />
                      <div className="ant-upload-text">上传</div>
                    </div>
                  )}
                </Upload>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={23} offset={1}>
            <FormItem label="备注">
              {getFieldDecorator('remark', {
                initialValue: currentItem.remark,
              })(<TextArea placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
        </Row>
        <div className={styles.fieldTitle}>资产信息</div>
        <Button
          onClick={() => {
            this.setState({ showModal: true })
          }}
          style={{ marginLeft: 135, marginBottom: 10 }}
        >
          添加资产
        </Button>
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          onClick={() => {
            this.handleSave()
          }}
        >
          保存提交
        </Button>
        <Table
          // loading={loading}
          size="small"
          bordered
          dataSource={propRecords}
          // rowKey={record => record.id}
          rowKey="id"
          pagination={false}
          columns={tableColumns}
          onChange={this.handleListChange}
          // rowSelection={rowSelectionProps}
        />
      </Form>
    )
  }

  // 渲染界面
  render() {
    // const { dispatch, submitting } = this.props
    // const { currentItem } = this.props.propRepair
    const modalProps = {
      showModal: this.state.showModal,
      storeState: this.props.propRepair,
      modalConfirmCallback: this.handleModalClick,
      modalCloseCallback: () => {
        this.setState({
          showModal: false,
        })
      },
    }
    // if (currentItem.id) {
    //   const selectRecords = {}
    //   const selectedRowKeys = currentItem.items.map(item => {
    //     selectRecords[item.id] = item
    //     return item.id
    //   })
    //   modalProps.selectRecords = selectRecords
    //   modalProps.selectedRowKeys = selectedRowKeys
    // }
    return (
      // TODO: 入库 or 编辑
      <PageHeaderWrapper title="报修单录入">
        <div className={styles.myContainer}>
          <Card className={styles.noPadding} bordered={false}>
            {this.renderForm()}
          </Card>
        </div>
        <PModal {...modalProps}></PModal>
      </PageHeaderWrapper>
    )
  }
}
